package com.wondersgroup.tjfx.controller.image;

import com.wondersgroup.tjfx.bo.inter.image.IImage;
import com.wondersgroup.tjfx.config.DefaultImageMap;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;

/**
 * 图片管理
 * 
 * @author lion
 * 
 */
@RestController
@RequestMapping("/image")
public class RestImageController {
	@Autowired
	IImage image;
	
	@Autowired
	DefaultImageMap defaultImage;

	
	/**
	 * 加载图片
	 * @param request
	 * @param response
	 * @throws IOException 
	 */
	@RequestMapping(value = "recriveImage/{id}")
	public String getImageById(HttpServletRequest request, HttpServletResponse response, @PathVariable("id") String id){
		String fileStr= "";
		try
		{
			//判断id是否是type类型，type类型表示为默认值，需要读取properties配置
			if(!StringUtils.isEmpty(id)&&id.startsWith("default_")){
				String type = id.replace("default_", "");
				id = defaultImage.get(type);;
			}
			
			fileStr=image.getImageByte(id);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return fileStr;
	}

	/**
	 * 查询所有图片
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "queryImage")
	public String queryImage(HttpServletRequest request) {
		return image.queryImage();
	}

	/**
	 * 新增图片
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/addImage",method=RequestMethod.POST)
	public String addImage(MultipartHttpServletRequest request, HttpServletResponse response) {
		Iterator<String> iter =  request.getFileNames();
	    String TPMS_LIST = request.getParameter("TPMS_LIST");
		try {
			TPMS_LIST = URLDecoder.decode(TPMS_LIST.toString(), "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		String[] ptms = TPMS_LIST.split(",");
		List<Map<String, Object>> files = new ArrayList<Map<String, Object>>();
		int i = 0;
		while(iter.hasNext())
		{
			String en = iter.next();
			List<MultipartFile> multipartFiles = request.getFiles(en);
			for (int j=0;j<multipartFiles.size();j++) {
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("TPMS", ptms[i++]);
				map.put("mFile", multipartFiles.get(j));
				files.add(map);
			}
		
		
		}
		return image.addImage(files);
	}
	
	/**
	 * 删除图片
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "deleteImage/{id}")
	public String deleteImage(@PathVariable("id") String id) {
		return image.deleteImage(id);
	}
}





















